<template>
  <div>
    <el-card style="margin-top:10px">
      <el-input :value="roleName" readonly />
    </el-card>
    <el-card style="margin-top:10px">
      <el-tree
        ref="tree"
        :data="data"
        show-checkbox
        node-key="id"
        style="margin-bottom:30px"
        default-expand-all
        highlight-current
        :props="defaultProps"
      />
      <el-button type="primary" @click="config">确认</el-button>
      <el-button type="info" @click="back">取消</el-button>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'RoleAuth',
  data() {
    return {
      id: '',
      roleName: '',
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      keysArr: []
    }
  },
  mounted() {
    this.id = this.$route.params.id
    this.roleName = this.$route.query.roleName
    this.getData()
  },
  methods: {
    async getData() {
      const res = await this.$api.permission.toAssign(this.id)
      if (res.code === 20000) {
        this.data = res.data.children
        this.keysArr = []
        this.getCheckedIds(this.data)
        this.$refs.tree.setCheckedKeys(this.keysArr)
      }
    },
    /*
      得到所有选中的id列表
      */
    getCheckedIds(auths) {
      auths.map(item => {
        // 如果被选中并且层级是4的话那么就添加进去
        if (item.select && item.level === 4) {
          this.keysArr.push(item.id)
          // 如果不是的话那么就重新执行一次这个函数去找符合条件的值
        } else if (item.children) {
          this.getCheckedIds(item.children)
        }
      })
    },
    back() {
      this.$router.back()
    },
    async config() {
      // 获取所有被选中的值
      this.keysArr = this.$refs.tree.getCheckedKeys()
      const res = await this.$api.permission.doAssign(this.id, this.keysArr.join())
      if (res.code === 20000) {
        this.$message({ type: 'success', message: '权限修改成功' })
        this.$router.back()
      }
    }
  }
}
</script>

<style>

</style>
